<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive, h } from 'vue'
import { ElTree, ElInput, ElDivider, ElTag } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import BasicManageApi from '@/api/linePatrol/Basicmanage'
import DrawData from './components/DrawData.vue'
import { XunLineAreaType } from '@/api/linePatrol/type'
import PipnentInfoApi from '@/api/equip/pipnet'
import { flatData } from '@/hooks/PublicFun'
const { t } = useI18n()
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const i = await BasicManageApi.GetXunLineAreaList({
      pnId: unref(currentNodeKey),
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await BasicManageApi.DeleXunLineArea(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'pnId',
    label: t('官网拓扑id'),
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return flatData(departmentList.value).map((item) => {
        if (item.id == cellValue) {
          return t(item.label)
        }
      })
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      },
      hidden: true
      // componentProps: {
      //   disabled: true,
      // },
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'leader',
    label: t('负责人'),
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '负责人'
      }
    },
    form: {
      hidden: false,
      colProps: {
        span: 20
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'pnName',
    label: t('官网拓扑名称'),
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 20
      }
      // hidden: true,
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'colour',
    label: t('颜色'),
    search: {
      hidden: true
    },
    form: {
      hidden: false,
      component: 'ColorPicker',
      colProps: {
        span: 20
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'isDraw',
    label: t('是否已绘制地图'),
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '是否绘制地图',
        options: [
          {
            label: '否',
            value: 0
          },
          {
            label: '是',
            value: 1
          }
        ]
      }
    },
    formatter: (_: Recordable, __: any, cellValue: number) => {
      return h(
        ElTag,
        {
          type: cellValue == 1 ? 'success' : 'danger'
        },
        () => (cellValue == 1 ? t('是') : t('否'))
      )
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 200,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
                {t('查看')}
              </span>
              <span class="TableBtn" onClick={() => draw(data.row)}>
                {t('绘制')}
              </span>
              <span
                class="TableBtn"
                style="color:rgb(212, 111, 13)"
                onClick={() => action(data.row, 'Edit')}
              >
                {t('修改')}
              </span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<any>([])
const fetchDepartment = async () => {
  const res = await PipnentInfoApi.GetPnTopologyTree()
  departmentList.value = res.data
  currentNodeKey.value = (res.data[0] && res.data[0].children && res.data[0].children[0].id) || ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
}
fetchDepartment()
const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: any) => {
  currentNodeKey.value = data.id
  currentPage.value = 1
  getList()
}

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.label.includes(value)
}

const dialogVisible = ref(false)
const MapdialogVisible = ref(false)
const dialogTitle = ref('')
const currentRow = ref<XunLineAreaType>()
const actionType = ref('')
const delLoading = ref(false)

const delData = async (row: XunLineAreaType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: any) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const draw = (row: XunLineAreaType) => {
  MapdialogVisible.value = true
  currentRow.value = row
  actionType.value == 'draw'
}
const action = (row: XunLineAreaType, type: string) => {
  actionType.value = type
  dialogVisible.value = true //打开弹窗
  if (type == 'add') {
    dialogTitle.value = '新增'
    currentRow.value = { pnId: Number(currentNodeKey.value) }
  } else if (type == 'Edit') {
    dialogTitle.value = '修改'
    currentRow.value = row
  } else if (type == 'Detail') {
    dialogTitle.value = '查看'
    currentRow.value = row
  }
}
const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    // saveLoading.value = false;
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await BasicManageApi.AddXunLineArea(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else if (actionType.value == 'Edit') {
      //修改字
      res.value = await BasicManageApi.EditXunLineArea(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      res.value = await BasicManageApi.EditXunLineArea(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
          MapdialogVisible.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px min-h-[580px]" title="片区拓扑">
      <div class="flex justify-center items-center">
        <ElInput
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('组织名称')"
          clearable
        />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'departmentName'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.label" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.label }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px" title="片区列表">
      <!-- <div class="flex"> -->
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="12" />新增
      </BaseButton>
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <!-- </div> -->
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog style="width: 500px" v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>

    <Dialog v-model="MapdialogVisible" title="绘制">
      <DrawData ref="writeRef" :current-row="currentRow" />
      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="MapdialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style scope>
.el-tree-node:focus > .el-tree-node__content {
  color: #409eff;
}
.CloseBtn {
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}

.TableBtn {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
